import { defineStore } from "pinia";
import api from "@/api";

export interface userStateTypes {
  userInfo: any | null;
  role: any | null;
  token: any;
}

const useUserStore = defineStore({
  id: "user",
  state: (): userStateTypes => ({
    userInfo: null,
    role: null, // 1 导师, 2 组长, 3 组员
    token: "",
  }),
  actions: {
    getToken(): String | null {
      if (this.token) {
        return this.token;
      }
      return localStorage.getItem("token");
    },

    async login(username: string, password: string) {
      return api.login.loginUser(username, password).then((res: any) => {
        this.token = res.data.token;
        this.userInfo = res.data.user;
        this.role = res.data.role.id;
        localStorage.setItem("roleId", res.data.role.id);
        localStorage.setItem("userAcc", res.data.user?.acc);
        localStorage.setItem("token", res.data.token);
      });
    },
    async getUserInfo(acc: string) {
      return api.user.selectUserByAcc(acc).then((res: any) => {
        this.userInfo = res.data;
      });
    },
  },
});

export default useUserStore;
